﻿/*MyPhotoIndex Free Photo Organizer <www.myphotoindex.com>
  Copyright (C) <2006-2009>  <Asaf Yarkoni asaf@yarkoni.net>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using MyPhotoIndex.Interfaces.Imaging;
using MyPhotoIndex.ImageBank;
using MyPhotoIndex.Utilities;

namespace MyPhotoIndex.Plugins.WebHost.RequestHandlers
{
    public class ThumbnailsRequestHandler : IRequestHandler
    {
        public void Process(HttpListenerRequest request, HttpListenerResponse response)
        {
            string fileName = Utils.GetRequestFileName(request);
            string fileExtention = Utils.GetRequestExtension(request);

            if (string.Compare(fileExtention, ".gif") != 0 &&
                string.Compare(fileExtention, ".jpg") != 0)
            {
                Utils.EndResponse(request, response, 404);
                return;
            }

            response.ContentType = Utils.GetContentTypeFromFileExtention(fileExtention);
            string contentDisposition = string.Empty;
            contentDisposition = string.Format("inline; filename={0}", fileName);
            response.AddHeader("content-disposition", contentDisposition);

            int imageId = Convert.ToInt32(Path.GetFileNameWithoutExtension(fileName));
            IImageData imageData = Storage.Instance.UnFiltered[imageId];

            Utils.SetCacheHeadersOneYear(response, imageData.LastModified);

            byte[] buffer = ThumbnailUtilities.ThumbnailToByteArray(imageData.Thumbnail);
            imageData.ThumbnailReferences++;
            imageData.ThumbnailReferences--;

            response.SendChunked = false;
            response.ContentLength64 = buffer.Length;
            using (Stream output = response.OutputStream)
            {
                output.Write(buffer, 0, buffer.Length);
                output.Flush();
            }
        }
    }
}
